package leetcode.code2049;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution implements IDebug {

	class Node {
//		int cur;
//		int parent;
		Node left;
		Node right;
		int size;
//		int leftSize;
//		int rightSize;

		public Node() {

		}

		public Node(int cur) {
//			this.cur = cur;
		}
	}

	long max;
	int ans;
	int n;

	public int countHighestScoreNodes(int[] parents) {
		max = 0;
		ans = 0;
		n = parents.length;
		Node[] hash = new Node[n];
		for (int i = 0; i < n; i++) {
			hash[i] = new Node();
		}
		for (int i = 1; i < n; i++) {
			int p = parents[i];
//			hash[i].parent = p;
			if (hash[p].left == null) {
				hash[p].left = hash[i];
			} else {
				hash[p].right = hash[i];
			}
		}
		Node info = this.f(hash[0]);
		if (info.left != null && info.right != null) {
			this.updateAns((long)info.left.size * info.right.size);
		} else if (info.left != null) {
			this.updateAns(info.left.size);
		} else {
			this.updateAns(info.right.size);
		}
		return ans;
	}

	private Node f(Node node) {
		if (node.left == null && node.right == null) {
			node.size = 1;
//			node.leftSize = 0;
//			node.rightSize = 0;
			this.updateAns((long)n - node.size);
		} else if (node.left == null && node.right != null) {
			Node right = this.f(node.right);
			node.size = right.size + 1;
			this.updateAns((long)right.size * (n - node.size));
//			node.leftSize = 0;
//			node.rightSize = right.size;
		} else if (node.left != null && node.right == null) {
			Node left = this.f(node.left);
			node.size = left.size + 1;
			this.updateAns((long)left.size * (n - node.size));
//			node.leftSize = left.size;
//			node.rightSize = 0;
		} else {
			Node right = this.f(node.right);
			Node left = this.f(node.left);
			node.size = right.size + left.size + 1;
			this.updateAns((long)right.size * left.size * (n - node.size));
//			node.leftSize = left.size;
//			node.rightSize = right.size;
		}
		return node;
	}

	private void updateAns(long num) {
		if (num > max) {
			max = num;
			ans = 1;
		} else if (num == max) {
			ans += 1;
		}
	}

	@Override
	public void debug1() {
		HelpDebug.compare(3, this.countHighestScoreNodes(HelpDebug.str2array3("[-1,2,0,2,0]")));

	}

	@Override
	public void debug2() {
		HelpDebug.compare(2, this.countHighestScoreNodes(HelpDebug.str2array3("[-1,2,0]")));

	}

	@Override
	public void debug3() {

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();

	}

}
